<template>
  <section class="flex flex-1 justify-center items-center flex-wrap">
    <div class="login-circle" />
    <el-image :src="Login" />
    <el-form ref="ruleFormRef" :model="loginForm" :rules="loginRules"
      class="animate__animated animate__fadeIn login-form">
      <el-row :gutter="20">
        <el-col :span="24" class="text-center">
          <el-image :src="LOGO" class="w-24 h-24" />
        </el-col>
      </el-row>
      <el-form-item prop="mobile">
        <el-input v-model="loginForm.mobile" type="text" size="large" auto-complete="off" placeholder="账号"
          @keyup.enter="handleLogin(ruleFormRef)">
          <template #prefix>
            <el-icon class="el-input__icon"><i-ep-User /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
          @keyup.enter="handleLogin(ruleFormRef)">
          <template #prefix>
            <el-icon class="el-input__icon"><i-ep-Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 55%"
          @keyup.enter="handleLogin(ruleFormRef)">
          <template #prefix>
            <el-icon class="el-input__icon"><i-ep-Promotion /></el-icon>
          </template>
        </el-input>
        <div class="login-code flex flex-1 justify-end">
          <div v-html="codeUrl" @click="getCode" class="login-code-img"></div>
        </div>
      </el-form-item>
      <el-row class="mb-[15px]">
        <el-col :span="12">
          <el-checkbox v-model="loginForm.rememberMe"> 记住密码 </el-checkbox>
        </el-col>
        <el-col :span="12">
          <router-link class="link-type" :to="'/register'">
            <div class="el-checkbox flex-row">
              <el-icon color="black"><i-ep-Pointer /></el-icon>
              <p style="font-size: 14px; padding-left: 8px">立即注册</p>
            </div>
          </router-link>
        </el-col>
      </el-row>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" style="width: 100%; background: #409eff; color: #fff"
          @click.prevent="handleLogin(ruleFormRef)">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script lang="ts" setup>
import UserService from "@/api/UserService";
import Login from "@/assets/img/login.svg";
import LOGO from "./../../assets/img/favicon.png";
import { emitter } from "@/common/event";
import { useAppStore } from "@/store";
import type { FormInstance, FormRules } from "element-plus";
import { Base64 } from 'js-base64'

const router = useRouter();
const app = useAppStore()
const loginForm = ref({
  mobile: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const loginRules = {
  mobile: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
const ruleFormRef = ref<FormInstance>();

const handleLogin = async (ruleFormRef: FormInstance | any) => {
  const result = await ruleFormRef?.validate().catch((e: any) => { });
  if (!result) return;

  if (loading.value) return;
  loading.value = true;
  const [err, res] = await UserService.login(loginForm.value);
  loading.value = false;
  if (err) {
    return Utils.Modal().msgError(err);
  }
  const userInfo = res.data || null
  Utils.saveLocal(Constant.LOGIN_TOKEN_KEY, userInfo)
  app.setUserInfo(userInfo)
  emitter.emit('refreshLogin', userInfo)

  const { rememberMe, mobile, password } = loginForm.value
  const params = {
    rememberMe,
    mobile,
    password: rememberMe ? Base64.encode(password) : ""
  }
  Utils.saveLocal(Constant.LOGIN_FORM_KEY, params)
  toPage()
  setTimeout(() => {
    reSetForm(ruleFormRef)
  }, 1000 * 1)
};

const reSetForm = (ruleFormRef: FormInstance) => {
  ruleFormRef.resetFields()
}

const getCode = async () => {
  const [err, res] = await UserService.getLoginCode();
  if (err) return Utils.Modal().msgError(err);
  const { data, text } = res.data || {};
  codeUrl.value = data;
  loginForm.value.uuid = text;
};

const getCookie = () => {
  const result = Utils.getLocal(Constant.LOGIN_FORM_KEY) || {}
  const { rememberMe, mobile, password } = result
  loginForm.value.rememberMe = rememberMe
  loginForm.value.mobile = mobile
  loginForm.value.password = password ? Base64.decode(password) : ""
  const userInfo = Utils.getLocal(Constant.LOGIN_TOKEN_KEY) || {}
  if (!Object.keys(userInfo).length) return
  emitter.emit('refreshLogin', userInfo)
  toPage()
}

const toPage = () => router.replace("/home")

getCookie();
getCode();
</script>

<style lang="scss" scoped>
.login-circle {
  background: #409eff;
  width: 1500px;
  height: 2000px;
  border-radius: 50%;
  position: fixed;
  top: -500px;
  left: -400px;
  z-index: 0;
}

.login-form {
  border-radius: 6px;
  height: 420px;
  background: #ffffff;
  width: 350px;
  padding: 25px 25px 5px 25px;
  box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.32);
  z-index: 99;
  margin: 10px auto;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }
}
</style>
